<template>
  <div class="serach-result">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="`${keyword}的搜索结果`"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->

    <!-- 文章列表 -->
    <van-list
      class="article-list"
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
    </van-list>
    <!-- /文章列表 -->
  </div>
</template>

<script>
import { getSearchRes } from "@/api/search.js";
export default {
  name: "SearchResult",
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      keyword: "",
      page: 1 //当前查询的页码
    };
  },
  created() {
    //获取参数 获取传入的查询关键字
    console.log(this.$route.query.keyword);
    this.keyword = this.$route.query.keyword;
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1);
      //   }
      //   // 加载状态结束
      //   this.loading = false;

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true;
      //   }
      // }, 500);
      try {
        //1.处理参数
        const keyword = this.keyword;
        const page = this.page;
        ////2.调用接口
        const res = await getSearchRes({
          q: keyword,
          page: page
        });
        // console.log(res);
        this.list.push(...res.data.data.results);
        //3.加载状态结束
        this.loading = false;
        this.page++;
        //4.根据我们的结果  判断 后端没有数据返回的时候不再加载
        if (res.data.data.results.length === 0) {
          this.finished = true;
        }
        //结果渲染
      } catch {
        //不再加载了
        this.finished = true;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.serach-result {
  height: 100%;
  overflow: auto;
  .article-list {
    margin-top: 39px;
  }
}
</style>
